package cn.itcast.bos.service.system.Impl;

import cn.itcast.bos.Dao.system.MenuRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuRepository menuRepository;
    @Override
    public List<Menu> findAll() {
        return menuRepository.findAll();
    }

    @Override
    public void save(Menu model) {
        //排除为选择父菜单,导致的父菜单id为null的情况
        if(model.getParentMenu().getId()==0){
            model.setParentMenu(null);
        }
        menuRepository.save(model);
    }

    @Override
    public List<Menu> findByUser() {
        //得到当前登陆的用户,通过用户查找对应得角色,然后查找对应得菜单列表
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if(user.getUsername().equals("smbe")){
            return menuRepository.findAll();
        }else{
            return menuRepository.findByUser(user.getId());
        }


    }
}
